package com.sites.cms.company;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.sites.common.SiteInfo;
import com.sites.common.model.Company;

/**
 * 公司信息服务层
 * 
 * @author zyg
 * 2021年10月31日 下午10:55:43
 */
public class CompanyService {
	
	private Company dao = new Company().dao();			

	public Company getCompany() {
		String sql = dao.getSql("company.getCompany");
		return dao.findFirst(sql, SiteInfo.siteId);
	}
	
	public Ret updateCompany(Company company) {
		Ret ret = Ret.create();
		Integer id = company.getId();
		if(id == null) {//此时是首次新增公司信息
			company.setSiteId(SiteInfo.siteId);
			boolean flag = company.save();
			if(flag){
				ret.setOk();
				ret.set(SiteInfo.msgKey, "保存成功");
				initCompanyInfo();//初始化公司信息
			} else {
				ret.setFail();
				ret.set(SiteInfo.msgKey, SiteInfo.serverError);
			}
			return ret;
		} else {//此时是更新公司信息
			Company temp = dao.findById(id);
			temp.setName(company.getName());
			temp.setAddress(company.getAddress());
			temp.setPostCode(company.getPostCode());
			temp.setContacts(company.getContacts());
			temp.setMobile(company.getMobile());
			temp.setTelephone(company.getTelephone());
			temp.setFax(company.getFax());
			temp.setQq(company.getQq());
			temp.setEmail(company.getEmail());
			temp.setLicense(company.getLicense());
			temp.setWebsite(company.getWebsite());
			temp.setRemark(company.getRemark());
			temp.setLogo(company.getLogo());
			temp.setWeChatImg(company.getWeChatImg());
			boolean flag = temp.update();
			if(flag){
				ret.setOk();
				ret.set(SiteInfo.msgKey, "更新成功");
				initCompanyInfo();//更新公司信息
			} else {
				ret.setFail();
				ret.set(SiteInfo.msgKey, SiteInfo.serverError);
			}
			return ret;
		}
	}
	
	/**
	 * 初始化公司信息
	 * 将公司信息缓存到SiteInfo的变量中
	 */
	public void initCompanyInfo() {
		String sql = dao.getSql("company.getCompany");
		Company company = dao.findFirst(sql, SiteInfo.siteId);
		if(company != null) {
			SiteInfo.company_name = company.getName();
			SiteInfo.company_address = company.getAddress();
			SiteInfo.company_postCode = company.getPostCode();
			SiteInfo.company_contacts = company.getContacts();
			SiteInfo.company_mobile = company.getMobile();
			SiteInfo.company_telephone = company.getTelephone();
			SiteInfo.company_fax = company.getFax();
			SiteInfo.company_qq = company.getQq();
			SiteInfo.company_email = company.getEmail();
			SiteInfo.company_website = company.getWebsite();
			SiteInfo.company_logo = company.getLogo();
			SiteInfo.company_weChatImg = company.getWeChatImg();
			SiteInfo.company_license = company.getLicense();
			SiteInfo.company_remark = company.getRemark();
		}
	}

	public Ret delSiteCompany(int siteId){
		Ret ret = Ret.ok();
		String sql = dao.getSql("company.delSiteCompany");
		Db.delete(sql, siteId);
		return ret;
	}
	
}
